package com.jml.service;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RFuture;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.LongCodec;
import org.redisson.client.protocol.RedisStrictCommand;
import org.redisson.command.CommandAsyncExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
public class SeckillRedisService {

    @Autowired
    private RedissonClient redissonClient;

    //默认，非公平锁
    @RequestMapping("/seckilRedisLock")
    public String seckilRedisLock(Long commodityId) throws Exception {
        RLock lock = null;
        try {
            // 获取可重入锁
            lock = redissonClient.getLock("MyRedisLockID");
            // uuid:88---redis
            // uuid:88 value+1 记录重入次数+1
            //leaseTime为-1
            lock.lock();
            Thread.sleep(30000);
            // 执行锁的业务逻辑
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (lock != null) {
                lock.unlock();
                log.info(">>释放锁<<");
            }
        }
        return "ok";
    }

    //默认，非公平锁
    @RequestMapping("/lock")
    public void testLock() throws Exception {
        t11();
    }

    /**
     * 指定超时时间
     */
    public void t0(){
        RLock lock = null;
        lock = redissonClient.getLock("MyRedisLockID");
        //leaseTime为-1,表示锁的默认时间是30s
        lock.lock();
        lock.unlock();
    }


    /**
     * 指定超时时间，当使用lock.lock()方法时，它是不会续期的。使用tryLock的时候，显示当前仍然锁还在。说明续期了。
     */
    public void t11() throws InterruptedException {
        RLock lock = null;
        lock = redissonClient.getLock("MyRedisLockID");
        lock.tryLock(3,TimeUnit.SECONDS);
        Thread.sleep(20000);
        lock.unlock();
    }

    /**
     * 指定超时时间
     */
    public void t1() throws InterruptedException {
        RLock lock = null;
        lock = redissonClient.getLock("MyRedisLockID");
        lock.lock(9,TimeUnit.SECONDS);
        Thread.sleep(20000);
        lock.unlock();
    }

    /**
     * 异步
     */
    public void t2(){
        RLock lock = null;
        lock = redissonClient.getLock("MyRedisLockID");
        lock.lockAsync();
        lock.lock(1,TimeUnit.SECONDS);
        lock.tryLockAsync(100,10,TimeUnit.SECONDS);
        lock.unlock();
    }

    /**
     * 公平锁
     */
    public void t3(){
        RLock lock = null;
        lock = redissonClient.getFairLock("MyRedisLockID");
        lock.lock(1,TimeUnit.SECONDS);
        lock.unlock();
    }

    /**
     * 红锁--暂时不用
     */

}
